﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using HRM.Properties;
using HRM.HRMServiceProxy;
using HRM.BusinessLogic;

namespace HRM
{


    public partial class FrmReturnInsBookList : FormBase
    {
        private readonly DoiSoClient _wcfDoiSo;
        private readonly EmployeeClient _wcfEmpl;
        private readonly RoleRightInfo _listRole;
        private string _selectedId = ",";
        private int _branchId = 0;
        private int _departmentId = 0;
        private bool _isFirstLoad = true;
        //
        private string PageOrderBy ="";

        protected class ReturnInsBookStatus
        {
            public readonly int None = 0;
            public readonly int Pending = 1;
            public readonly int Approved = 2;
        }

        public FrmReturnInsBookList()
        {
            InitializeComponent();
            _isFirstLoad = true;
            _wcfDoiSo = Service.DoiSo();
            _listRole = UIParamater.Quyen_DeNghiCapSoBH;
            _wcfEmpl = Service.Employee();
            UISetting.LoadTreeView3(ref tvBranch);
            btnPrint.Enabled = _listRole.Create;
            FillComBoBoxReturnInsBookStatus();

            if (cbReturnInsBookStatus.ComboBox != null)
            {
                var type = Convert.ToInt32(cbReturnInsBookStatus.ComboBox.SelectedValue);
                var returnInsBookStatus = new ReturnInsBookStatus();
                btnPending.Visible = type == returnInsBookStatus.None;
                BtnApproval.Visible = type == returnInsBookStatus.Pending && Program.isChuyenQuan;
            }

            ShowHideCommandButton();
            
            pager.AllowChangePageSize = true;
            
        }

        public override void Show_Form()
        {
            Show();
        }

        protected override void Init_Control()
        {
            InitGrid();
            //
            //
            BindData();
        }


        /// <summary>
        /// Nạp dữ liệu về trạng thái
        /// </summary>
        private void FillComBoBoxReturnInsBookStatus()
        {
            var dt = new DataTable();
            dt.Columns.Add("Ma");
            dt.Columns.Add("Ten");
            var returnInsBookStatus = new ReturnInsBookStatus();
            dt.Rows.Add(returnInsBookStatus.None, "Chưa trả thẻ");
            dt.Rows.Add(returnInsBookStatus.Pending, "Đang chờ trả thẻ");
            dt.Rows.Add(returnInsBookStatus.Approved, "Đã trả thẻ");

            if (cbReturnInsBookStatus.ComboBox != null)
            {
                cbReturnInsBookStatus.ComboBox.DisplayMember = "Ten";
                cbReturnInsBookStatus.ComboBox.ValueMember = "Ma";
                cbReturnInsBookStatus.ComboBox.DataSource = dt;
                cbReturnInsBookStatus.ComboBox.SelectedIndex = 0;
            }
        }

        /// <summary>
        /// Định nghĩa các cột cho DataGridView
        /// </summary>
        private void InitGrid()
        {
            dtgData.Columns.Clear();

            //Thêm cột Checkbox
            var col = new DataGridViewCheckBoxColumn
                          {
                              DefaultCellStyle = { Alignment = DataGridViewContentAlignment.MiddleCenter },
                              Name = "Check",
                              HeaderText = HrmResources.COLUMN_HEADERTEXT_SELECT,
                              Width = 50
                          };

            col.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleLeft;
            dtgData.Columns.Add(col);
            col.Visible = true;

            var arrColumn = new List<DataGridViewColumn>
                                {
                                    FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("STT","RN", 50),
                                    FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("Số sổ BH","Employee_SiBookNo", 80),
                                    FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("Số thẻ","Employee_CardNo", 100),
                                    FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("Họ và tên","Employee_FullName", 120),
                                    FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("Ngày sinh","Employee_DateOfBirth", 120),
                                    FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("Phòng ban","Department_Name", 120),
                                    FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("Chức vụ","Position_Name", 120),
                                    FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("PA cuối", "Detail_InsTypeCode", 40),
                                    FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("Ngày trả thẻ","ReturnInsBook_Date", 120),
                                    FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("Employee_Id", "Employee_Id",0, "", false),
                                    FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("ReturnInsBook_Id", "ReturnInsBook_Id", 0)
                                };

            FormGlobals.Grid_Init(dtgData, arrColumn, "", 1);
        }

        /// <summary>
        /// Lấy dữ liệu danh sách nhân viên
        /// </summary>
        private void BindData()
        {
            
            BtnEpThuHoiThe.Visible = false;
            chkAll.Checked = false;
            chkAll.Visible = true;

            if (cbReturnInsBookStatus.ComboBox != null)
            {
                var sType = Convert.ToInt32(cbReturnInsBookStatus.ComboBox.SelectedValue.ToString());

                DataTable dt = null;
                var returnInsBookStatus = new ReturnInsBookStatus();

                
                    if (sType.Equals(returnInsBookStatus.None))
                    {
                        //Danh sách cán bộ đang chờ chốt sổ hoặc đã chốt sổ nhưng chưa trả thẻ + ds cán bộ đang tham gia đóng BH nhưng chưa trả thẻ.
                        dt = Detail_Controller.Instance().DSThamGiaBH(Program.strBranchCode, chkBaoGiam.Checked ? "G" : "", _departmentId, pager.PageIndex,pager.PageSize,PageOrderBy);
                    }
                    else if (sType.Equals(returnInsBookStatus.Pending) || sType.Equals(returnInsBookStatus.Approved))
                    {
                        //Danh sách cán bộ chờ trả thẻ và đã được trả thẻ
                        dt = ReturnInsBook_Controller.Instance().ReturnInsBook_GetAll(_branchId, sType, pager.PageIndex, pager.PageSize, PageOrderBy);
                    }
                    

                if (dt == null) return;
                if (dt.TableName.Contains("ERROR")) return;
                //
                pager.TotalRow = dt.Rows.Count > 0 ? Globals.Object_GetValue<int>(dt.Rows[0]["TotalCount"]) : 0;
                var rowCount = dt.Rows.Count;

                if (rowCount > 0)
                {
                    if (dt.Columns.Contains("Check"))
                        dt.Columns["Check"].DefaultValue = false;

                    BtnEpThuHoiThe.Visible = (sType == returnInsBookStatus.Pending);
                }

                if (rowCount > 1)
                    chkAll.Visible = true;

                if (txtKeyWord.Text != "")
                    dt.DefaultView.RowFilter = "Employee_SiBookNo Like '%" + txtKeyWord.Text + "%' OR Employee_FullName Like '%" + txtKeyWord.Text + "%'";

                dtgData.DataSource = dt;
            }
        }

        /// <summary>
        /// Lấy chuỗi Employee_ID được chọn
        /// </summary>
        private void GetSelectedId()
        {
            foreach (DataGridViewRow row in dtgData.Rows)
            {
                if (Convert.ToBoolean(row.Cells["Check"].Value))
                {
                    if (!_selectedId.Contains("," + row.Cells["Employee_ID"].Value + ","))
                    {
                        _selectedId += row.Cells["Employee_ID"].Value + ",";
                    }
                }
                else
                {
                    var sOld = "," + row.Cells["Employee_ID"].Value + ",";
                    if (_selectedId.Contains(sOld))
                        _selectedId = _selectedId.Replace(sOld, ",");
                }
            }
        }

        /// <summary>
        /// Lọc danh sách theo phòng ban
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TvBranchAfterSelect(object sender, TreeViewEventArgs e)
        {
            txtKeyWord.Text = "";
            if (e.Node.Level == 0)
            {
                if (Program.isAdmin || Program.isViewAll)
                {
                    _branchId = 0;
                    _departmentId = 0;
                }
                else
                    _branchId = Program.intBranchID;
                //
               
            }
            else if (e.Node.Level == 1)
            {
                _branchId = Convert.ToInt32(e.Node.Tag);
                _departmentId = 0;
            }
            else if (e.Node.Level >= 2)
            {
                _departmentId = Convert.ToInt32(e.Node.Tag);
                _branchId = Convert.ToInt32(e.Node.Parent.Tag);
            }
            //
            pager.PageIndex = 0;
            if (!IsLoading && e.Node.Level > 0 )
            //
            {
                FormGlobals.App_ProgressShow(delegate()
                {
                    BindData();
                }, "");
            }
        }


        /// <summary>
        /// Đổ lại dữ liệu cán bộ
        /// </summary>
        private void BtnFindClick()
        {
            pager.PageIndex =0;
            _selectedId = "";
            if (!IsLoading) 
            BindData();
        }

        /// <summary>
        /// Xử lý sự kiện CheckedChanged của nút chọn tất cả
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ChkCheckAllCheckedChanged(object sender, EventArgs e)
        {
            if (chkAll.Checked)
            {
                for (var i = 0; i < dtgData.Rows.Count; i++)
                {
                    dtgData.Rows[i].Cells["Check"].Value = true;
                }
                GetSelectedId();
            }
            else
            {
                for (var i = 0; i < dtgData.Rows.Count; i++)
                {
                    dtgData.Rows[i].Cells["Check"].Value = false;
                }
                _selectedId = "";
            }

        }

        /// <summary>
        /// Xử lý sự kiện IndexChanged trạng thái
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CbReturnInsBookStatusSelectedIndexChanged(object sender, EventArgs e)
        {
            var returnInsBookStatus = new ReturnInsBookStatus();
            if (cbReturnInsBookStatus.ComboBox != null &&
                cbReturnInsBookStatus.ComboBox.SelectedValue.ToString().Equals(returnInsBookStatus.None.ToString(CultureInfo.CurrentCulture)))
                dtgData.MultiSelect = false;
            else
                dtgData.MultiSelect = true;

            ShowHideCommandButton();

            pager.PageIndex = 0;
            if (!IsLoading)
            {
                FormGlobals.App_ProgressShow(delegate()
                {
                    BindData();
                }, "");
            }
        }

        /// <summary>
        /// Xử lý sự kiện Click nút chờ duyệt
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnPendingClick(object sender, EventArgs e)
        {
            dtgData.EndEdit();
            var dataGridViewRowCollection = dtgData.Rows;
            var returnInsBookStatus = new ReturnInsBookStatus();

            var passed = (from DataGridViewRow row in dataGridViewRowCollection
                          where Convert.ToBoolean(row.Cells["Check"].Value)
                          select new ReturnInsBookInfo
                                     {
                                         ReturnInsBook_BranchId = Program.intBranchID,
                                         ReturnInsBook_EmployeeId = Globals.Object_GetValue<int>(row.Cells["Employee_Id"].Value),
                                         ReturnInsBook_FullName = Globals.Object_GetValue<string>(row.Cells["Employee_FullName"].Value),
                                         ReturnInsBook_SiBookNo = Globals.Object_GetValue<string>(row.Cells["Employee_SiBookNo"].Value),
                                         ReturnInsBook_CardNo = Globals.Object_GetValue<string>(row.Cells["Employee_CardNo"].Value),
                                         ReturnInsBook_Type = returnInsBookStatus.Pending
                                     }).All(infor => ReturnInsBook_Controller.Instance().ReturnInsBook_Insert(infor) > 0);

            if (passed)
            {
                pager.PageIndex = 0;
                if (!IsLoading)
                    FormGlobals.App_ProgressShow(delegate()
                    {
                        BindData();
                    }, "");
            }
        }

        /// <summary>
        /// Xử lý kiện Click nút Duyệt
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnApprovalClick(object sender, EventArgs e)
        {
            dtgData.EndEdit();
            var dataGridViewRowCollection = dtgData.Rows;
            var returnInsBookStatus = new ReturnInsBookStatus();

            var passed = (from DataGridViewRow row in dataGridViewRowCollection
                          where Convert.ToBoolean(row.Cells["Check"].Value)
                          select new ReturnInsBookInfo
                                     {
                                         ReturnInsBook_Id = Globals.Object_GetValue<int>(row.Cells["ReturnInsBook_Id"].Value),
                                         ReturnInsBook_Type = returnInsBookStatus.Approved
                                     }).All(infor => !ReturnInsBook_Controller.Instance().ReturnInsBook_Update(infor));

            if (passed)
            {
                if (!IsLoading)
                    FormGlobals.App_ProgressShow(delegate()
                    {
                        BindData();
                    }, "");
            }

            // Đổ lại danh sách nhân viên cho bộ nhớ tạm
            LocalDB.dtTableEmployee = _wcfEmpl.Employee_GetAllWithBranch(Program.intBranchID).Tables[0];



            // BindData();
        }

        private void BtnDelClick(object sender, EventArgs e)
        {
            dtgData.EndEdit();
            var dataGridViewRowCollection = dtgData.Rows;

            foreach (DataGridViewRow row in dataGridViewRowCollection)
                if (Convert.ToBoolean(row.Cells["Check"].Value))
                {
                    ReturnInsBook_Controller.Instance().ReturnInsBook_Delete(
                        Globals.Object_GetValue<int>(row.Cells["ReturnInsBook_Id"].Value));
                }

            //
            pager.PageIndex = 0;
            if (!IsLoading)
                FormGlobals.App_ProgressShow(delegate()
                {
                    BindData();
                }, "");
        }

        /// <summary>
        /// Xử lý việc kích hoạt các nút
        /// </summary>
        private void ShowHideCommandButton()
        {
            btnDel.Visible = false;
            btnPending.Visible = false;
            BtnApproval.Visible = false;
            btnCapso.Visible = false;
            btnPrint.Visible = false;

            if (cbReturnInsBookStatus.ComboBox == null) return;

            var sType = Convert.ToInt32(cbReturnInsBookStatus.ComboBox.SelectedValue);
            var returnInsBookStatus = new ReturnInsBookStatus();

            if (sType.Equals(returnInsBookStatus.None))
            {
                btnPending.Visible = true;
            }
            else if (sType.Equals(returnInsBookStatus.Pending))
            {
                btnDel.Visible = true;
                BtnApproval.Visible = true;
                btnPrint.Visible = true;
            }
            else if (sType.Equals(returnInsBookStatus.Approved))
            {
                //btnDel.Visible = Program.isChuyenQuan;
                btnDel.Visible = true;
            }
        }

        /// <summary>
        /// Xử lý sự kiện Click nút cấp sổ
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnCapsoClick(object sender, EventArgs e)
        {
            _selectedId = "";
            GetSelectedId();
            if (_selectedId == "," || _selectedId == "")
            {
                MessageBox.Show(HrmResources.YOU_HAVE_NO_SELECTED_EMPLOYEES, HrmResources.NOTIFY, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            _wcfDoiSo.HRM_Doiso_CapNhatDeNghiCapSo(Program.intBranchID, "C", _selectedId.StartsWith(",") ? _selectedId.Substring(1) : _selectedId, "", DateTime.Now);
            _selectedId = "";
            if (!IsLoading)
                FormGlobals.App_ProgressShow(delegate()
                {
                    BindData();
                }, "");

        }

        private void BtnFindClick1(object sender, EventArgs e)
        {
            FormGlobals.App_ProgressShow(new MethodInvoker(() =>
            {
                BtnFindClick();
            }), "Đang lấy dữ liệu");
        }

        /// <summary>
        /// Xử lý sự kiện Click của nút In
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MnuPrintPendingClick(object sender, EventArgs e)
        {
            var returnInsBookStatus = new ReturnInsBookStatus();
            var f = new frmPreviewReport("InDanhSachChoTraThe", new[] { _branchId.ToString(CultureInfo.CurrentCulture), Convert.ToString(returnInsBookStatus.Pending) });
            f.Show(this);
        }

        private void TxtKeyWordKeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                BtnFindClick();
            }

        }

        private void FrmReturnInsBookList_Load(object sender, EventArgs e)
        {
        }

        private void BtnEpThuHoiThe_Click(object sender, EventArgs e)
        {
            var dt = (DataTable)dtgData.DataSource;
            if (!dt.Columns.Contains("NGAYGIAM"))
                dt.Columns.Add("NGAYGIAM", typeof(DateTime));
            if (!dt.Columns.Contains("MAGIAM"))
                dt.Columns.Add("MAGIAM", typeof(string));

            //


            //
            var dv = dt.DefaultView;
            ExcelColumn item = null;
            var columns = new List<ExcelColumn>();

            item = new ExcelColumn { FieldName = "Employee_SIBookNo", HeaderText = "SOBHXH", DataFormat = "", Width = 100 };
            columns.Add(item);
            item = new ExcelColumn { FieldName = "Employee_CardNo", HeaderText = "SOTHE", DataFormat = "", Width = 100 };
            columns.Add(item);
            item = new ExcelColumn { FieldName = "Employee_FullName", HeaderText = "HOTEN", DataFormat = "", Width = 100 };
            columns.Add(item);
            item = new ExcelColumn { FieldName = "NGAYGIAM", HeaderText = "NGAYGIAM", DataFormat = "dd/MM/yyyy", Width = 100 };
            columns.Add(item);
            item = new ExcelColumn { FieldName = "MAGIAM", HeaderText = "MAGIAM", DataFormat = "", Width = 100 };
            columns.Add(item);

            //
            //Xây dựng các cột trước

            DataTable dtTmp = dv.ToTable();
            dtTmp.Columns.Remove("Check");
            for (int i = 0; i < dtTmp.Columns.Count; i++)
            {
                dtTmp.Columns[i].ColumnName = UnicodeConvert.UnicodeToTCVN3(dtTmp.Columns[i].ColumnName);
            }
            //Gán dữ liệu vào các dòng tương ứng theo cột

            for (int j = 0; j < dtTmp.Rows.Count; j++)
            {
                for (int idx = 0; idx < dtTmp.Columns.Count; idx++)
                {
                    if (dtTmp.Columns[idx].DataType == typeof(String))
                        dtTmp.Rows[j][idx] = UnicodeConvert.UnicodeToTCVN3(dtTmp.Rows[j][idx].ToString());
                }
            }
            //

            var fileName = ExcelHelper.Excel_Export(dtTmp.DefaultView, columns);
            if (String.IsNullOrEmpty(fileName)) return;
            try
            {
                System.Diagnostics.Process.Start(fileName);
            }
            catch (Exception ex)
            {
                MessageBox.Show(string.Format(HrmResources.CAN_NOT_OPEN_FILE, fileName), HrmResources.NOTIFY);
            }
        }

        private void chkBaoGiam_Checked_Changed(object sender, EventArgs e)
        {
            FormGlobals.App_ProgressShow(new MethodInvoker(() =>
            {
                BtnFindClick();
            }), "Đang lấy dữ liệu");
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            splitContainer1.Panel1Collapsed = !splitContainer1.Panel1Collapsed;
            toolStripButton1.Image = splitContainer1.Panel1Collapsed ? Properties.Resources.right16 : Properties.Resources.left16;
        }

        //
        private void pager_PageIndex_Changed(int Idx)
        {
            if (!IsLoading)
                FormGlobals.App_ProgressShow(delegate()
                {
                    BindData();
                }, "");
        }
    }
}
